package com.example.jpa.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import java.util.Map;

/**
 * 主库事务配置
 * @author 86188
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "slaveManagerFactory",
        transactionManagerRef = "slaveTransactionManager",
        basePackages = {"com.example.jpa.slave"}
)
public class DruidTransactionSlaveConfig {

    @Autowired
    @Qualifier("slaveDataSource")
    private javax.sql.DataSource slaveDataSource;

    @Autowired
    JpaProperties jpaProperties;
    /**获取jpa配置信息*/
    private Map<String, String> getVendorProperties() {
        return jpaProperties.getProperties();
    }

    @Bean(name = "slaveManagerFactory")
    public LocalContainerEntityManagerFactoryBean slaveManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(slaveDataSource).properties(getVendorProperties()).packages("com.example.jpa.pojo").persistenceUnit("slavePersistenceUnit").build();
    }

    @Bean(name = "slaveEntityManager")
    public EntityManager slaveEntityManager(EntityManagerFactoryBuilder builder) {
        return slaveManagerFactory(builder).getObject().createEntityManager();
    }

    @Bean(name = "slaveTransactionManager")
    public PlatformTransactionManager slaveTransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(slaveManagerFactory(builder).getObject());
    }
}
